package com.wptk.filemanager.utils;

import android.R
import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import java.util.*


/**
 * @author dr
 * @date 2020-05-22
 * @description 中间层, 需要增加工具, 或者增加公用功能可以在这module增加
 */
object ManagerActivityUtils {

    private val taskMap: MutableMap<String, ActivityLifeCallback?> = HashMap()

    /**
     * 维护Activity 的list
     */
    private val mActivity: MutableList<Activity> = Collections.synchronizedList(LinkedList())

    //region 管理activity类
    fun addTask(taskKey: String, callback: ActivityLifeCallback?) {
        if (TextUtils.isEmpty(taskKey) || callback == null) {
            return
        }
        taskMap[taskKey] = callback
    }

    fun removeTask(taskKey: String) {
        if (TextUtils.isEmpty(taskKey)) {
            return
        }
        if (taskMap[taskKey] == null) {
            return
        }
        taskMap.remove(taskKey)
    }

    /**
     * @param activity 作用说明 ：添加一个activity到管理里
     */
    fun pushActivity(activity: Activity) {
        mActivity.add(activity)
        //Logx.d("activityList:size:" + mActivity.size)
    }

    /**
     * @param activity 作用说明 ：删除一个activity在管理里
     */
    fun popActivity(activity: Activity) {
        mActivity.remove(activity)
        //Logx.d("activityList:size:" + mActivity.size)
    }

    /**
     * get current Activity 获取当前Activity（栈中最后一个压入的）
     */
    fun currentActivity(): Activity? {
        return if (mActivity.isEmpty()) null else mActivity[mActivity.size - 1]
    }

    /**
     * 结束当前Activity（栈中最后一个压入的）
     */
    fun finishCurrentActivity() {
        if (mActivity.isEmpty()) {
            return
        }
        val activity: Activity = mActivity[mActivity.size - 1]
        finishActivity(activity)
    }

    /**
     * 结束指定的Activity
     */
    fun finishActivity(activity: Activity) {
        if (mActivity.isEmpty()) {
            return
        }
        mActivity.remove(activity)
        activity.finish()
    }

    /**
     * 结束指定类名的Activity
     */
    fun finishActivity(cls: Class<*>) {
        if (mActivity.isEmpty()) {
            return
        }
        for (activity in mActivity) {
            if (activity.javaClass == cls) {
                finishActivity(activity)
            }
        }
    }

    /**
     * 按照指定类名找到activity
     *
     * @param cls
     * @return
     */
    fun findActivity(cls: Class<*>): Activity? {
        var targetActivity: Activity? = null
        for (activity in mActivity) {
            if (activity.javaClass == cls) {
                targetActivity = activity
                break
            }
        }
        return targetActivity
    }

    /**
     * @return 作用说明 ：获取当前最顶部activity的实例
     */
    fun getTopActivity(): Activity? {
        var mBaseActivity: Activity?
        synchronized(mActivity) {
            val size: Int = mActivity.size - 1
            if (size < 0) {
                return null
            }
            mBaseActivity = mActivity[size]
        }
        return mBaseActivity
    }

    /**
     * @return 作用说明 ：获取当前最顶部的acitivity 名字
     */
    fun getTopActivityName(): String? {
        var mBaseActivity: Activity?
        synchronized(mActivity) {
            val size: Int = mActivity.size - 1
            if (size < 0) {
                return null
            }
            mBaseActivity = mActivity[size]
        }
        return mBaseActivity!!.javaClass.name
    }

    /**
     * 结束所有Activity
     */
    fun finishAllActivity() {
        for (activity in mActivity) {
            activity.finish()
        }
        mActivity.clear()
    }


    /**
     * 退出应用程序
     */
    fun appExit() {
        try {
            Log.d("ManagerActivityUtils","app exit");
            finishAllActivity()
        } catch (e: Exception) {
        }
    }

    fun registerActivityListener(context: Application) {
        context.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                /**
                 * 监听到 Activity创建事件 将该 Activity 加入list
                 */
                pushActivity(activity)
                for (callback in taskMap.values) {
                    if (callback == null) {
                        continue
                    }
                    callback.onCreated(activity, savedInstanceState)
                }
            }

            private var foregroundActivities = 0
            private val isChangingConfiguration = false
            override fun onActivityStarted(activity: Activity) {
                foregroundActivities++
                if (foregroundActivities == 1 && !isChangingConfiguration) {
//                    IsReception = true
                    // 应用切到前台
                    //Logx.d("onActivityStarted font")
                    Log.d("ManagerActivityUtils","onActivityStarted font");
                }
                for (callback in taskMap.values) {
                    if (callback == null) {
                        continue
                    }
                    callback.onStarted(activity)
                }
            }

            override fun onActivityStopped(activity: Activity) {
                foregroundActivities--
                if (foregroundActivities == 0) {
//                    IsReception = false
                    // 应用切到后台
                    //Logx.d("onActivityStarted back")
                    Log.d("ManagerActivityUtils","onActivityStarted back");
                }
                for (callback in taskMap.values) {
                    if (callback == null) {
                        continue
                    }
                    callback.onStopped(activity)
                }
            }

            //            override fun onActivityStarted(activity: Activity) {}
            override fun onActivityResumed(activity: Activity) {
                for (callback in taskMap.values) {
                    if (callback == null) {
                        continue
                    }
                    callback.onResumed(activity)
                }
            }

            override fun onActivityPaused(activity: Activity) {
                for (callback in taskMap.values) {
                    if (callback == null) {
                        continue
                    }
                    callback.onPaused(activity)
                }
            }

            //            override fun onActivityStopped(activity: Activity) {}
            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

            override fun onActivityDestroyed(activity: Activity) {
                if (mActivity.isEmpty()) {
                    return
                }
                if (mActivity.contains(activity)) {
                    /**
                     * 监听到 Activity销毁事件 将该Activity 从list中移除
                     */
                    popActivity(activity)
                }
                for (callback in taskMap.values) {
                    if (callback == null) {
                        continue
                    }
                    callback.onDestroyed(activity)
                }
            }
        })
    }


    /**
     * 判断某个界面是否在前台
     *
     * @param activity 要判断的Activity
     * @return 是否在前台显示
     */
    open fun isForeground(activity: Activity): Boolean {
        return isForeground(activity, activity.javaClass.name)
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    open fun isForeground(context: Context?, className: String): Boolean {
        if (context == null || TextUtils.isEmpty(className)) return false
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val list = am.getRunningTasks(1)
        if (list != null && list.size > 0) {
            val cpn = list[0].topActivity
            if (className == cpn!!.className) return true
        }
        return false
    }


    /**
     * 将本应用置顶到最前端
     * 当本应用位于后台时，则将它切换到最前端
     *
     * @param activity
     */
    open fun setTopApp(activity: Activity) {
        /**获取ActivityManager */
        val intent = Intent(activity, activity.javaClass)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
        activity.application.startActivity(intent) //getApplication()不可以去掉否则没用
    }

    open fun getRootView(context: Activity): View? {
        return (context.findViewById<View>(R.id.content) as ViewGroup).getChildAt(0)
    }

    interface ActivityLifeCallback {
        fun onCreated(activity: Activity?, savedInstanceState: Bundle?)
        fun onStarted(activity: Activity?)
        fun onResumed(activity: Activity?)
        fun onPaused(activity: Activity?)
        fun onStopped(activity: Activity?)
        fun onDestroyed(activity: Activity?)
    }


}